<template>
    <el-form ref="formRef" label-width="100px">
        <el-form-item label="SPU名称">
            <el-input placeholder="请输入SPU名称" v-model="spuParams.spuName"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌">
            <el-select v-model="spuParams.tmId" placeholder="请选择SPU品牌">
                <el-option v-for="tm in allTradeMark" :key="tm.id" :label="tm.tmName"
                    :value="tm.id as number"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="请输入SPU描述" v-model="spuParams.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU照片">
            <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload" list-type="picture-card"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeUploadHandler">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: 100%;" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU销售属性">
            <el-select v-model="saleAttrIdAndValueName" style="width: 200px;"
                :placeholder="unSelectSaleAttr.length > 0 ? '还有' + unSelectSaleAttr.length + '个未选择' : '没有未选择'">
                <el-option v-for="item in unSelectSaleAttr" :key="item.id" :label="item.name"
                    :value="`${item.id}:${item.name}`"></el-option>
            </el-select>
            <el-button @click="addSaleAttr" :disabled="!saleAttrIdAndValueName" style="margin-left: 10px;"
                type="primary" icon="Plus">添加销售属性</el-button>
            <el-table :border="true" style="margin: 10px 0;" :data="saleAttr">
                <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
                <el-table-column label="销售属性名字" width="120" prop="saleAttrName"></el-table-column>
                <el-table-column label="销售属性值">
                    <template #default="scope">
                        <el-tag closable @close="scope.row.spuSaleAttrValueList.splice(index, 1)"
                            v-for="(item, index) in scope.row.spuSaleAttrValueList" :key="item.id" style="margin: 5px">
                            {{ item.saleAttrValueName }}
                        </el-tag>
                        <el-input v-if="scope.row.flag" v-model="scope.row.saleAttrValue" @blur="toLook(scope.row)"
                            placeholder="请输入属性值" size="small" style="width: 100px;" />
                        <el-button v-else @click="toEdit(scope.row)" type="primary" size="small"
                            icon="Plus"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120px">
                    <template #default="scope">
                        <el-button type="danger" size="small" icon="Delete"
                            @click="saleAttr.splice(scope.$index, 1)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>

    </el-form>
</template>

<script setup lang="ts">
import { reqAllSaleAttr, reqAllTradeMark, reqSpuHasSaleAttr, reqSpuImageList, reqAddOrUpdateSpu } from '@/api/product/spu';
import type { AllTradeMark, HasSaleAttr, HasSaleAttrResponseData, SaleAttr, SaleAttrResponseData, SaleAttrValue, SpuData, SpuHasImg } from '@/api/product/spu/type';
import type { TradeMark } from '@/api/product/trademark/type';
import { ElMessage, type UploadUserFile } from 'element-plus';

import { computed, ref } from 'vue';

let $emit = defineEmits(["changeScene"]);

const cancel = () => {
    $emit("changeScene", { num: 0, flag: 'update' });
}
//存储已有的spu数据
let allTradeMark = ref<TradeMark[]>([])
//存储已有的spu图片
let imgList = ref<UploadUserFile[]>([])
//存储已有的spu销售属性
let saleAttr = ref<SaleAttr[]>([])
//存储全部的spu销售属性
let allSaleAttr = ref<HasSaleAttr[]>([])
let dialogVisible = ref(false)
let dialogImageUrl = ref('')
//存储已有的spu对象
let spuParams = ref<SpuData>({
    category3Id: '',
    spuName: '',
    tmId: '',
    description: '',
    spuImageList: [],
    spuSaleAttrList: []
})
let saleAttrIdAndValueName = ref<string>('')
const initHasSpuData = async (spu: SpuData) => {
    spuParams.value = spu
    //获取全部品牌的数据
    let result: AllTradeMark = await reqAllTradeMark()
    //获取某个品牌旗下全部售卖商品的图片
    let result1: SpuHasImg = await reqSpuImageList(spu.id as number)
    //获取已有的spu销售属性的数据
    let result2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
    //获取整个项目全部spu销售属性的数据
    let result3: HasSaleAttrResponseData = await reqAllSaleAttr()

    allTradeMark.value = result.data
    //result1.data赋值给imgList
    imgList.value = result1.data.map(item => {
        return {
            name: item.imgName || '',
            url: item.imgUrl
        }
    })
    saleAttr.value = result2.data
    allSaleAttr.value = result3.data
}
const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
}
const handleRemove = (file: any) => {
    imgList.value = imgList.value.filter(item => item.uid !== file.uid)
}
const beforeUploadHandler = (file: any) => {
    if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        ElMessage.error('上传图片格式必须是 JPG|PNG|GIF format!')
        return false
    }
    if (file.size / 1024 / 1024 > 2) {
        ElMessage.error('上传图片大小不能超过 2MB!')
        return false
    }
    return true
}
//计算出当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
    //全部销售属性:颜色、版本、尺码
    //已有的销售属性:颜色、版本
    let unSelectArr = allSaleAttr.value.filter((item) => {
        return saleAttr.value.every((item1) => {
            return item.name != item1.saleAttrName
        })
    })
    return unSelectArr
})
//添加销售属性的方法
const addSaleAttr = () => {
    let [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
    let newSaleAttr: SaleAttr = {
        baseSaleAttrId: parseInt(baseSaleAttrId),
        saleAttrName,
        spuSaleAttrValueList: []
    }
    saleAttr.value.push(newSaleAttr)
    saleAttrIdAndValueName.value = ''
}
const toEdit = (row: SaleAttr) => {
    row.flag = true
    row.saleAttrValue = ''
}
const toLook = (row: SaleAttr) => {
    row.flag = false
    const { baseSaleAttrId, saleAttrValue } = row
    let newSaleAttrValue: SaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: saleAttrValue || '',
    }
    //判断用户输入的销售属性值是否为空
    if (saleAttrValue?.trim() === '') return
    //判断该销售属性值是否已经存在
    let isRepeat = row.spuSaleAttrValueList.some(item => item.saleAttrValueName === saleAttrValue)
    if (isRepeat) {
        ElMessage.warning('属性值不能重复')
        return
    }

    row.spuSaleAttrValueList.push(newSaleAttrValue)
}

const save = () => {
    spuParams.value.spuImageList = imgList.value.map(item => {
        return {
            imgName: item.name,
            imgUrl: item.url || (item.response as any)?.data
        }
    })
    // console.log(spuParams.value)
    spuParams.value.spuSaleAttrList = saleAttr.value
    reqAddOrUpdateSpu(spuParams.value).then(res => {
        if (res.code === 200) {
            ElMessage.success('保存成功')
            $emit("changeScene", { num: 0, flag: 'add' });
        } else {
            ElMessage.error(res.message)
        }
    })
}

//添加一个新的spu初始化请求方法
const initAddSpu = async (c3Id: number | string) => {
    //清空spuParams数据
    Object.assign(spuParams.value, {
        category3Id: '',
        spuName: '',
        tmId: '',
        description: '',
        spuImageList: [],
        spuSaleAttrList: []
    })
    //清空照片墙
    imgList.value = []
    //清空销售属性
    saleAttr.value = []
    spuParams.value.category3Id = c3Id
    //获取全部品牌的数据
    let result: AllTradeMark = await reqAllTradeMark()
    //获取整个项目全部spu销售属性的数据
    let result1: HasSaleAttrResponseData = await reqAllSaleAttr()
    //存储数据
    allTradeMark.value = result.data
    allSaleAttr.value = result1.data
    saleAttrIdAndValueName.value = ''
}
//对外暴露
defineExpose({
    initHasSpuData,
    initAddSpu
})
</script>

<style scoped></style>